package ar.edu.unlu.sistemas.ws.business;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class PeerManager {

	private static PeerManager instance;
	private Map<String,PeerWS> peers = new HashMap<String,PeerWS>();
	private Integer sequence = 1;
	
	private PeerManager() {
		sequence = this.getSequence();
	}
	private Integer getSequence() {
		try {
			 ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("/home/pepo/Escritorio/sequence")));
			 return (Integer) ois.readObject();
		} catch (Exception e) {
			return 1;
		}
	}
	private void incSequence() {
		try {
			 ObjectOutputStream ois = new ObjectOutputStream(new FileOutputStream(new File("/home/pepo/Escritorio/sequence")));
			 sequence++;
			 ois.writeObject(sequence);
		} catch (Exception e) {
		}
	}
	public static PeerManager getInstance() {
		if (instance == null) {
			instance = new PeerManager();
		}
		return instance;
	}
	
	public synchronized Integer addPeer(PeerWS peer) {
		if ("".equals(peer.getId()) || peer.getId() == null || !this.peers.containsKey(peer.getId())) {
			peer.setId(this.sequence.toString());
			peer.setStatus(1);
			this.peers.put(peer.getId(), peer);
			Integer ant = sequence;
			this.incSequence();
			return ant++;
		} else {
			return -1;
		}
	}
	
	public synchronized Boolean hasPeer(PeerWS peer) {
		if (!"".equals(peer.getId()) && peer.getId() != null) return this.peers.containsKey(peer.getId());
		else return false;
	}
	
	public synchronized Integer enablePeer(PeerWS peer) {
		if (this.peers.containsKey(peer.getId())) {
			peer.setStatus(1);
			this.peers.put(peer.getId(), peer);
			return new Integer(peer.getId());
		} else {
			return -1;
		}
	}
	
	public synchronized Integer disablePeer(PeerWS peer) {
		if (this.peers.containsKey(peer.getId())) {
			this.peers.get(peer.getId()).setStatus(0);
			return new Integer(peer.getId());
		} else {
			return -1;
		}
	}
	
	public synchronized Set<String> getPeers() {
		return this.peers.keySet();
	}
	
	public synchronized PeerWS getPeer(String peerId) {
		return this.peers.get(peerId);
	}
	
}
